<template>
  <view class="container">
    <view class="info-item">
    	<label class="label">品牌方：</label>
    	<view class="input">
			<dict-label dict-type="oper_station_source" :value="station.source" />
		</view>
    </view>
    <view class="info-item">
    	<label class="label">运维方：</label>
    	<view class="input">
			<dict-label dict-type="oper_station_operation" :value="station.operation" />
		</view>
    </view>
    <view class="info-item">
    	<label class="label">运维要求：</label>
    	<view class="input">{{ station.request }}</view>
    </view>
    <view class="info-item">
    	<label class="label">建站时间：</label>
    	<view class="input">{{ parseTime(station.buildTime) }}</view>
    </view>
    <view class="info-item">
    	<label class="label">交接时间：</label>
    	<view class="input">{{ parseTime(station.connetTime) }}</view>
    </view>
    <view class="info-item">
    	<label class="label">电站编号：</label>
    	<view class="input">{{ station.stationno }}</view>
    </view>
    <view class="info-item">
    	<label class="label">电站名称：</label>
    	<view class="input">{{ station.name }}</view>
    </view>
    <view class="info-item">
    	<label class="label">装机容量：</label>
    	<view class="input">{{ station.totalpower/1000 }} kW</view>
    </view>
    <view class="info-item">
    	<label class="label">业主姓名：</label>
    	<view class="input">{{ station.guestname }}</view>
    </view>
    <view class="info-item">
    	<label class="label">业主手机：</label>
    	<view class="input">{{ station.phone }}</view>
    </view>
	<view class="info-item">
		<label class="label">省：</label>
		<view class="input">{{ station.provinceId }}</view>
	</view>
	<view class="info-item">
		<label class="label">市：</label>
		<view class="input">{{ station.cityId }}</view>
	</view>
	<view class="info-item">
		<label class="label">区：</label>
		<view class="input">{{ station.areaId }}</view>
	</view>
	<view class="info-item">
		<label class="label">镇：</label>
		<view class="input">{{ station.townId }}</view>
	</view>
    
    <view class="info-item">
    	<label class="label">电站地址：</label>
    	<view class="input">{{ station.addressstring }}</view>
    </view>
	<view class="info-item">
		<label class="label">电站坐标：</label>
		<view class="input">({{ station.latitude }}, {{ station.longitude }})</view>
		<button @click="getLocation">更新</button>
	</view>
    <!-- 坐标输入 -->
<!--    <view class="form-item" @click="chooseLocation">
      <text class="label">位置：</text>                                                     
      <view v-if="station.latitude && station.longitude">
        <map :longitude="station.longitude" :latitude="station.latitude" scale="15" show-compass show-scale @click="chooseLocation"></map>
      </view>
      <view v-else>
        <map :longitude="location.longitude" :latitude="location.latitude" scale="15" show-compass show-scale @click="chooseLocation"></map>
      </view>
      <view class="map-overlay"></view>
    </view> -->

    <!-- 上传类型选择标签 -->
    <view class="upload-type-tabs">
      <view 
        v-for="(label, type) in uploadTypes" 
        :key="type"
        :class="['type-tab', {active: currentUploadType === type}]"
        @click="currentUploadType = type"
      >
        {{label}}
      </view>
    </view>

    <!-- 图片上传区域 -->
    <view class="upload-header">
      <text class="label">{{ uploadTypes[currentUploadType] }}：</text>
    </view>
    <view class="upload-grid">
      <view v-for="(img, index) in previewImages[currentUploadType]" :key="index" class="image-wrapper">
        <image :src="img" class="uploaded-image" mode="aspectFill" @click="previewImage(index, currentUploadType)" />
        <view class="delete-icon" @click="removeImage(index, currentUploadType)">✖</view>
      </view>
      <view class="upload-add" @click="chooseImage">
        <image src="/static/camera-icon.png" class="camera-icon" mode="aspectFit" />
      </view>
    </view>
	
	<!-- 未填写照片原因 -->
	<view>
	  <view class="form-label">未填写照片原因：</view>
	  <textarea 
	    v-model="station.reason" 
	    placeholder="请详细填写未填写照片原因" 
	    class="text-area" 
	  />
	</view>

    <!-- 提交按钮 -->
    <button class="submit-btn" @click="handleSubmit">提交更新</button>
  </view>
</template>

<script>
import request from '@/utils/request.js'; 
import { getAccessToken } from '@/utils/auth';  
import config from '@/config'
import QQMapWX from '@/utils/qqmap-wx-jssdk.min.js'
import { parseTime } from '@/utils/ruoyi' // ✅ 路径改为 ruoyi.js


export default {
  data() {
    return {
      stationId: "",
      station: {
        gatePicUrls: [],
        invPicUrls: [],
        colPicUrls: [],
		ammPicUrls: [],
		comPicUrls: [],
		locationPicUrls: [],
		addressstring:"",
		provinceId : "",
		cityId : "",
		areaId : "",
		townId : "",
		reason : "",
      },
      location: {
        longitude: '',
        latitude: '',
      },
	  qqmapKey: getApp().globalData.config.appInfo.qqmapKey,
      token: '',
      // 上传相关数据
      uploadTypes: {
        gate: '电站门头照片',
        inv: '逆变器照片',
        col: '采集器照片',
		amm: '电表箱照片',
		com: '电站俯视图',
		location: '电站周围15米方位图'
      },
      currentUploadType: 'location', // 当前上传类型
      previewImages: {
        gate: [],  // 位置图片预览
        inv: [], // 设备图片预览
        col: [],   // 文档图片预览
		amm: [],  // 位置图片预览
		com: [], // 设备图片预览
		location: [],   // 文档图片预览
      },
      uploading: false // 上传状态
    }
  },
  async onLoad(options) {
    this.token = await getAccessToken('token')
    // this.initialMap()
    
    if (!options.id) {
      uni.showToast({ title: '缺少站点ID', icon: 'none' });
      //setTimeout(() => uni.navigateBack(), 1500);
      return;
    }
    
    this.stationId = Number(decodeURIComponent(options.id));
    this.fetchStationDetails(this.stationId);
  },
  methods: {
	  parseTime, // ✅ 挂在 methods 里，供模板使用
    async fetchStationDetails(id) {
      try {
        const response = await request({ url: `/oper/station/get?id=${id}`, method: 'GET' });
        if (response.code === 0) {
          this.station = response.data;
          // 初始化预览图片
          if (this.station.locationPicUrls) {
            this.previewImages.location = [...this.station.locationPicUrls];
          }
          if (this.station.gatePicUrls) {
            this.previewImages.gate = [...this.station.gatePicUrls];
          }
          if (this.station.invPicUrls) {
            this.previewImages.inv = [...this.station.invPicUrls];
          }
		  if (this.station.colPicUrls) {
		    this.previewImages.col = [...this.station.colPicUrls];
		  }
		  if (this.station.ammPicUrls) {
		    this.previewImages.amm = [...this.station.ammPicUrls];
		  }
		  if (this.station.comPicUrls) {
		    this.previewImages.com = [...this.station.comPicUrls];
		  }
        }
      } catch (error) {
        uni.showToast({ title: '加载失败', icon: 'none' });
      }
    },
    
    // 图片预览
    previewImage(index, type) {
      uni.previewImage({
        current: this.previewImages[type][index],
        urs: this.previewImages[type]
      });
    },
    
    // 选择图片
    chooseImage() {
      if (this.uploading) return;
      
      uni.chooseImage({
        count: 9 - this.previewImages[this.currentUploadType].length, // 最多9张
        sizeType: ['compressed'], // 压缩图
        sourceType: ['album', 'camera'], // 相册和相机
        success: (res) => {
          this.uploadFiles(res.tempFilePaths);
        }
      });
    },
    
    // 上传文件
    uploadFiles(filePaths) {
      this.uploading = true;
      uni.showLoading({ title: '上传中...', mask: true });
      
      const uploadTasks = filePaths.map(filePath => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: config.baseUrl + config.baseApi + '/infra/file/upload',
            header: { 
              Authorization: `Bearer ${this.token}`,
              'X-File-Type': this.currentUploadType
            },
            filePath: filePath,
            name: 'file',
            success: (res) => {
              try {
                const data = JSON.parse(res.data);
                if (data.code === 0) {
                  resolve(data.data);
                } else {
                  reject(new Error(data.msg || '上传失败'));
                }
              } catch (e) {
                reject(new Error('解析响应失败'));
              }
            },
            fail: (err) => {
              reject(new Error(err.errMsg || '上传失败'));
            }
          });
        });
      });
      
      Promise.all(uploadTasks)
        .then(urls => {
          this.previewImages[this.currentUploadType].push(...urls);
          this.station[`${this.currentUploadType}PicUrls`] = this.previewImages[this.currentUploadType];
          uni.showToast({ title: '上传成功', icon: 'success' });
        })
        .catch(err => {
          uni.showToast({ title: err.message, icon: 'none' });
        })
        .finally(() => {
          this.uploading = false;
          uni.hideLoading();
        });
    },
    
    // 删除图片
    removeImage(index, type) {
      this.previewImages[type].splice(index, 1);
      this.station[`${type}PicUrls`] = this.previewImages[type];
    },
    
    // 位置选择
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.station.latitude = res.latitude;
          this.station.longitude = res.longitude;
        },
        fail: () => {
          uni.showToast({ title: '位置选择失败', icon: 'none' });
        }
      });
    },
    
    // initialMap() {
    //   uni.getLocation({
    //     type: 'wgs84',
    //     success: (res) => {
    //       this.location.longitude = res.longitude;
    //       this.location.latitude = res.latitude;
    //     },
    //     fail: (err) => {
    //       console.error('获取位置失败：', err);
    //     }
    //   });
    // },
	// getLocation(){
	// 	uni.getLocation({
	// 	  type: 'wgs84',
	// 	  isHighAccuracy:true,
	// 	  highAccuracyExpireTime:4000,
	// 	  success: (res) => {
	// 	    this.station.longitude = res.longitude;
	// 	    this.station.latitude = res.latitude;
	// 	  },
	// 	  fail: (err) => {
	// 	    console.error('获取位置失败：', err);
	// 	  }
	// 	});
	// },
	getLocation(){
		uni.getLocation({
		  type: 'gcj02',  
		  isHighAccuracy:true,
		  highAccuracyExpireTime:4000,
		  success: (res) => {
			console.log(res);
		    this.station.longitude = res.longitude;
		    this.station.latitude = res.latitude;
			this.reverseGeocoder();
		  },
		  fail: (err) => {
		    console.error('获取位置失败：', err);
		  }
		});
	},
	
	//解析经纬度
	reverseGeocoder(){
		var _this = this;
		var qqmapsdk = new QQMapWX({
		    key: this.qqmapKey
		}); 
		console.log(qqmapsdk);
		 qqmapsdk.reverseGeocoder({
		      //位置坐标，默认获取当前位置，非必须参数
		   //Object格式
			location: {
			  latitude: this.station.latitude,
			  longitude: this.station.longitude
			},
		      /**
		       *
		       //String格式
		        location: '39.984060,116.307520',
		      */
		      //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
		      success: function(res) {//成功后的回调
		        console.log(res);
		        var res = res.result;
				_this.station.addressstring = res.formatted_addresses.standard_address;
				var adcode = res.ad_info.adcode;
				_this.station.provinceId = adcode.slice(0, 2) + "0000";
				_this.station.cityId = adcode.slice(0, 4) + "00";
		        _this.station.areaId = adcode;
				_this.station.townId = res.address_reference.town.id;
				_this.station.address = res.formatted_addresses.recommend;
		        
		      },
		      fail: function(error) {
		        console.error(error);
		      },
		      complete: function(res) {
				console.log(res);
		      }
		    })
		
	},
    
    // 提交表单
    async handleSubmit() {
      try {
        uni.showLoading({ title: '提交中...', mask: true });
        
        const response = await request({
          url: '/oper/station/update',
          method: 'PUT',
          headers: { 
            Authorization: `Bearer ${this.token}`,
            'Content-Type': 'application/json'
          },
          data: {
            ...this.station,
            id: this.stationId
          },
        });
        
        uni.hideLoading();
        
        if (response.code === 0) {
          uni.showToast({ title: '更新成功' });
          setTimeout(() => uni.navigateBack(), 1500);
        } else {
          throw new Error(response.msg || '更新失败');
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({ 
          title: error.message || '提交失败', 
          icon: 'none',
          duration: 3000
        });
        console.error('提交失败:', error);
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  padding: 24rpx;
  background-color: white;
}

.info-item {
  margin-bottom: 20rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #333;
}

.input {
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 80rpx;
}

.form-item {
  margin: 32rpx 0;
}

/* 上传类型标签 */
.upload-type-tabs {
  display: flex;
  margin: 30rpx 0 20rpx;
  border-bottom: 1rpx solid #eee;
}

.type-tab {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
  
  &.active {
    color: #007AFF;
    font-weight: bold;
    
    &::after {
      content: '';
      position: absolute;
      bottom: -1rpx;
      left: 30rpx;
      right: 30rpx;
      height: 4rpx;
      background-color: #007AFF;
    }
  }
}

/* 上传区域 */
.upload-header {
  margin: 20rpx 0 10rpx;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.image-wrapper {
  position: relative;
  width: 100%;
  aspect-ratio: 1 / 1;
  border-radius: 8rpx;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-icon {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
}

.upload-add {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  aspect-ratio: 1 / 1;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  background-color: #f9f9f9;
}

.camera-icon {
  width: 60rpx;
  height: 60rpx;
  opacity: 0.5;
}

/* 地图样式 */
map {
  width: 100%;
  height: 300rpx;
  border-radius: 8rpx;
}

.map-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

/* 提交按钮 */
.submit-btn {
  margin-top: 60rpx;
  background: #007AFF;
  color: white;
  border-radius: 8rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
}

.submit-btn:active {
  opacity: 0.8;
}
</style>
